// pages/home/home.js
var Util = require('../../utils/util.js');
const db = wx.cloud.database()
const _ = db.command
Page({
  /**
   * 页面的初始数据
   */
  data: {
    tabs: ["支出", "收入", "转账", "还款"],
    currentDate: Util.getCurrentDate(),
    activeIndex: 0,
    sliderOffset: 0,
    sliderLeft: 0,
    cateId: 0,
    assetId: 0,
    chooseFiles: [],
    deleteIndex: -1,
    choosed_cate1: '',
    choosed_cate2: '',
    cateImg_path1:'',
    cateImg_path2:'',
    choosed_asset1: '',
    choosed_asset2: '',
    assetImg1_path: '',
    assetImg2_path: '',
    amount: '',
    desc: '',
    type: '',
    fileID: [],
    budget: 0
  },

  tabChange: function(e) {
    //根据选中组件设置分类页面list
    var cateId = e.currentTarget.dataset.cateId;
    console.log("cateId"+cateId);
    this.setData({
      cateId:cateId
    })

    this.setData({
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndex: e.currentTarget.id
    });
  },

  //选择本地照片
  chooseImage:function(event){
    var imgArr = this.data.chooseFiles;
    var leftCount = 3-imgArr.length;

    if(leftCount<=0){
      return;
    }

    wx.chooseImage({
      count: leftCount,
      sourceType: ['album', 'camera'],
      success: (result) => {
        this.setData({
          chooseFiles:imgArr.concat(result.tempFilePaths)
        })
      }
    })
  },

  //删除已经选择的图片
  deleteImage:function (event) {
    var index = event.currentTarget.dataset.idx,
        that=this;
    that.setData({
      deleteIndex:index
    });
    that.data.chooseFiles.splice(index,1);
    setTimeout(function () {
      that.setData({
        deleteIndex:-1,
        chooseFiles:that.data.chooseFiles
      });
    },500)
  },

  // 提交表单
  formSubmit: function(event) {
    let files = this.data.chooseFiles
    let fileID = []
    if (this.data.cateId == 0) {
      this.setData({
        type: '支出'
      })
    }
    else if (this.data.cateId == 1) {
      this.setData({
        type: '收入'
      })
    }
    else if (this.data.cateId == 2) {
      this.setData({
        type: '转账'
      })
    }
    else if (this.data.cateId == 3) {
      this.setData({
        type: '还款'
      })
    }
    console.log(this.data.type)
    if (files.length != 0) {
      for (let i = 0; i < files.length; i++) {
        let curDatetime = new Date().getTime()
        wx.cloud.uploadFile({
          cloudPath: curDatetime + this.data.openid,
          filePath: files[i],
          success: res => {
            fileID.push(res.fileID)
            if (fileID.length == files.length) {
              if (this.data.cateId == 0 || this.data.cateId == 1) {
                if (event.detail.value.amount == '') {
                  wx.showToast({
                    title: '金额不能为0',
                    icon:'success',
                    image:"../../images/failed.png"
                  })
                  return
                }
                else if (event.detail.value.cate == '') {
                  wx.showToast({
                    title: '未选择分类',
                    icon:'success',
                    image:"../../images/failed.png"
                  })
                  return
                }
                else if (event.detail.value.account == '') {
                  wx.showToast({
                    title: '未选择账户',
                    icon:'success',
                    image:"../../images/failed.png"
                  })
                  return
                }
                let _type = this.data.cateId == 0 ? '支出':'收入'
                db.collection('user_bill').add({
                  data: {
                    amount: parseFloat(event.detail.value.amount),
                    type: _type,
                    cate: event.detail.value.cate,
                    account: event.detail.value.account,
                    datetime: event.detail.value.datetime,
                    desc: event.detail.value.desc,
                    imgs: fileID
                  },
                  success(res) {
                    wx.showToast({
                      title: '记账成功！',
                    })
                    if (getCurrentPages().length != 0) {

                      //刷新当前页面的数据
          
                      getCurrentPages()[getCurrentPages().length - 1].onLoad()
          
                    }
                  },
                  fail(res) {
                    wx.showToast({
                      title: '记账失败！',
                      icon:'success',
                    image:"../../images/failed.png"
                    })
                  }
                })
              }
              else if (this.data.cateId == 2 || this.data.cateId == 3) {
                if (event.detail.value.amount == '') {
                  wx.showToast({
                    title: '金额不能为0',
                    icon:'success',
                    image:"../../images/failed.png"
                  })
                  return
                }
                else if (event.detail.value.account1 == '') {
                  wx.showToast({
                    title: '未选择转出账户',
                    icon:'success',
                    image:"../../images/failed.png"
                  })
                  return
                }
                else if (event.detail.value.account1 == '') {
                  wx.showToast({
                    title: '未选择转入账户',
                    icon:'success',
                    image:"../../images/failed.png"
                  })
                  return
                }
                let _type = this.data.cateId == 2 ? '转账':'还款'
                db.collection('user_bill').add({
                  data: {
                    amount: parseFloat(event.detail.value.amount),
                    type: _type,
                    account1: event.detail.value.account1,
                    account2: event.detail.value.account2,
                    datetime: event.detail.value.datetime,
                    desc: event.detail.value.desc,
                    imgs: fileID
                  },
                  success(res) {
                    wx.showToast({
                      title: '记账成功！',
                    })
                    if (getCurrentPages().length != 0) {

                      //刷新当前页面的数据
          
                      getCurrentPages()[getCurrentPages().length - 1].onLoad()
          
                    }
                  },
                  fail(res) {
                    wx.showToast({
                      title: '记账失败！',
                      icon:'success',
                    image:"../../images/failed.png"
                    })
                  }
                })
              }
            }
          }
        })
      }
    }
    else {
      if (this.data.cateId == 0 || this.data.cateId == 1) {
        if (event.detail.value.amount == '') {
          wx.showToast({
            title: '金额不能为0',
            icon:'success',
                    image:"../../images/failed.png"
          })
          return
        }
        else if (event.detail.value.cate == '') {
          wx.showToast({
            title: '未选择分类',
            icon:'success',
                    image:"../../images/failed.png"
          })
          return
        }
        else if (event.detail.value.account == '') {
          wx.showToast({
            title: '未选择账户',
            icon:'success',
                    image:"../../images/failed.png"
          })
          return
        }
        db.collection('user_bill').add({
          data: {
            amount: parseFloat(event.detail.value.amount),
            type: this.data.type,
            cate: event.detail.value.cate,
            account: event.detail.value.account,
            datetime: event.detail.value.datetime,
            desc: event.detail.value.desc,
          },
          success(res) {
            wx.showToast({
              title: '记账成功！',
              icon:'success'
            })
            if (getCurrentPages().length != 0) {

              //刷新当前页面的数据
  
              getCurrentPages()[getCurrentPages().length - 1].onLoad()
  
            }
          },
          fail(res) {
            wx.showToast({
              title: '记账失败！',
              icon:'success',
                    image:"../../images/failed.png"
            })
          }
        })
      }
      else if (this.data.cateId == 2 || this.data.cateId == 3) {
        if (event.detail.value.amount == '') {
          wx.showToast({
            title: '金额不能为0',
            icon:'success',
                    image:"../../images/failed.png"
          })
          return
        }
        else if (event.detail.value.account1 == '') {
          wx.showToast({
            title: '未选择转出账户',
            icon:'success',
                    image:"../../images/failed.png"
          })
          return
        }
        else if (event.detail.value.account1 == '') {
          wx.showToast({
            title: '未选择转入账户',
            icon:'success',
                    image:"../../images/failed.png"
          })
          return
        }
        db.collection('user_bill').add({
          data: {
            amount: parseFloat(event.detail.value.amount),
            type: this.data.type,
            account1: event.detail.value.account1,
            account2: event.detail.value.account2,
            datetime: event.detail.value.datetime,
            desc: event.detail.value.desc,
          },
          success(res) {
            wx.showToast({
              title: '记账成功！',
            })
            if (getCurrentPages().length != 0) {

              //刷新当前页面的数据
  
              getCurrentPages()[getCurrentPages().length - 1].onLoad()
  
            }
          },
          fail(res) {
            wx.showToast({
              title: '记账失败！',
              icon:'success',
                    image:"../../images/failed.png"
            })
          }
        })
      }
    }
    this.setData({
      chooseFiles: [],
      deleteIndex: -1,
      choosed_cate1: '',
      choosed_cate2: '',
      cateImg_path1:'',
      cateImg_path2:'',
      choosed_asset1: '',
      choosed_asset2: '',
      assetImg1_path: '',
      assetImg2_path: '',
      amount: '',
      desc: '',
      type: '',
      fileID: [],
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    if (getCurrentPages().length != 0) {

      //刷新当前页面的数据

      getCurrentPages()[getCurrentPages().length - 1].onLoad()

    }
  },

  // 修改日期渲染
  bindPayDateChange: function(event) {
    this.setData({
      currentDate: event.detail.value
    })
  },
  
  dateToString: function(date) { 
    let year = date.getFullYear(); 
    let month = (date.getMonth() + 1).toString(); 
    let day = (date.getDate()).toString();  
    if (month.length == 1) { 
      month = "0" + month; 
    } 
    if (day.length == 1) { 
      day = "0" + day; 
    }
    let dateTime = year + "-" + month + "-" + day;
    return dateTime; 
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '首页',
    })
    this.dataLoading()
  },

dataLoading:function(){
  var that = this
    wx.cloud.callFunction({
      name: 'login',
      success: res => {
        this.setData({
          openid: res.result.openid
        })
        db.collection("user_budget").where({
          _openid: this.data.openid
        }).get().then(function(res) {
          if (res.data.length == 0) {
            that.setData({
              budget: 0
            })
            db.collection("user_budget").add({
              data: {
                budget: 0
              }
            })
          }
          else {
            that.setData({
              budget: res.data[0].budget
            })
          }
          let date = new Date()
          db.collection("user_bill").aggregate().match({
            _openid: that.data.openid,
            type: '支出',
            datetime: _.gte(that.dateToString(new Date(date.getFullYear(), date.getMonth(), 1)))
          }).group({
            _id: '$type',
            sum: _.aggregate.sum('$amount')
          }).end().then(function(res) {
            if (res.list.length == 0) {
              that.setData({
                totalPaymentMonth: 0
              })
            }
            else {
              that.setData({
                totalPaymentMonth: res.list[0].sum
              })
            }
            console.log(that.data.totalPaymentMonth)
          })
          db.collection("user_bill").aggregate().match({
            _openid: that.data.openid,
            type: '支出',
            datetime: Util.getCurrentDate()
          }).group({
            _id: '$type',
            sum: _.aggregate.sum('$amount')
          }).end().then(function(res) {
            if (res.list.length == 0) {
              that.setData({
                totalPaymentToday: 0
              })
            }
            else {
              that.setData({
                totalPaymentToday: res.list[0].sum
              })
            }
            console.log(that.data.totalPaymentToday)
          })
        })
      }
    })
},

  //跳转选择分类页面
  toCategoryChoosePage(){
    wx.navigateTo({
      url: '../home/categoryChoose?id='+this.data.cateId
    })
  },

  //跳转选择账户页面
  toAssetChoosePage(e){
    var assetId = e.currentTarget.dataset.assetId;
    wx.navigateTo({
      url: '../home/assetChoose?id='+assetId
    })
  },

  //修改预算
  onTapToSetBudget(){
    wx.navigateTo({
      url: '../setBudget/setBudget?openid=' + this.data.openid + '&totalMonth=' + this.data.totalPaymentMonth + '&totalToday=' + this.data.totalPaymentToday
    })
  },
})